<?php

/**
 *    售货员控制器，其扮演实际交易中柜台售货员的角色，你可以这么理解她：你告诉我（售货员）要买什么东西，我会询问你你要的收货地址是什么之类的问题
 *        并根据你的回答来生成一张单子，这张单子就是“订单”
 *
 *    @author    Garbin
 *    @param    none
 *    @return    void
 */
class OrderApp extends ShoppingbaseApp {

    function __construct() {
        $this->OrderApp();
    }

    function OrderApp() {
        parent::__construct();
        $this->mod_msg = & m('msg');
        $this->mod_msglog = & m('msglog');
    }

    /**
     *    填写收货人信息，选择配送，支付方式。
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function index() {
        $goods_info_array = $this->_get_goods_info();
        if ($goods_info_array === false) {
            /* 购物车是空的 */
            $this->show_warning('goods_empty');

            return;
        }
        $integral_enabled= Conf::get('integral_enabled') ? true : false;    // 获取系统是否开启积分
        foreach($goods_info_array as $goods_info){
        /*  检查库存 */
        $goods_beyond = $this->_check_beyond_stock($goods_info['items']);
        if ($goods_beyond) {
            $str_tmp = '';
            foreach ($goods_beyond as $goods) {
                $str_tmp .= '<br /><br />' . $goods['goods_name'] . '&nbsp;&nbsp;' . $goods['specification'] . '&nbsp;&nbsp;' . Lang::get('stock') . ':' . $goods['stock'];
            }
            $this->show_warning(sprintf(Lang::get('quantity_beyond_stock'), $str_tmp));
            return;
        }
        }
        if (!IS_POST) {
            /* 根据商品类型获取对应订单类型 */
            import('init.lib');
            $goods_mod = & m('goods');
            $address_model = & m('address');
            $model_region = & m('region');
            $goods_type = & gt($goods_info['type']);
            $order_type = & ot($goods_info['otype']);
            /*foreach开始*/
            foreach($goods_info_array as $key => $goods_info){


            /* 显示订单表单 */
            $shipping_data = $order_type->get_order_form($goods_info['store_id']); 
            if ($shipping_data === false) {
                $this->show_warning($order_type->get_error());

                return;
            }
            $goods_info_array[$key]['shipping_data']=$shipping_data;
            $goods_info_array[$key]['is_free_fee']=0;
            /*满包邮 GEGIN*/
            // 放到数组里，对应stores
            $logic1 = FALSE;
            if ($goods_info['enable_free_fee']) {
                (($goods_info['amount'] >= $goods_info['amount_for_free_fee']) && ($goods_info['amount_for_free_fee'] > 0)) && $logic1 = true;
                $logic2 = ($goods_info['quantity'] >= $goods_info['acount_for_free_fee']) && ($goods_info['acount_for_free_fee'] > 0);
                if ($logic1 || $logic2) {
                    $logic2 && $title = sprintf(Lang::get('free_acount_ship_title'), $goods_info['acount_for_free_fee']);
                    $logic1 && $title = sprintf(Lang::get('free_amount_ship_title'), $goods_info['amount_for_free_fee']);
                $goods_info_array[$key]['is_free_fee']=1;
                $goods_info_array[$key]['free_fee_name']=$title;
                }
            }
            /*满包邮 END*/
                   
            $goods_info_array[$key]['coupon_list']=Init_OrderApp::get_available_coupon($goods_info['store_id'],$goods_info_array[$key]['items']);
                $total_integral_max_exchange = 0; #共可使用多少积分进行抵扣
                
                foreach ($goods_info['items'] as $goods) {
                    // 因为一个订单可能包含多个商品,一个商品可能购买了M件，那么可使用的积分便是 N*M 之和
                    $goods_integral = $goods_mod->get($goods['goods_id']); #当前产品设置的积分抵扣额
                    $total_integral_max_exchange += $goods_integral['integral_max_exchange'] * $goods['quantity'];
                }
                $goods_info_array[$key]['total_integral_max_exchange']=$total_integral_max_exchange;
                
        }
                $member_mod = & m('member');
                $member_info = $member_mod->get($this->visitor->get('user_id'));
                $this->assign('member_info', $member_info);
            /*foreach结束*/
            if ($integral_enabled) {

                //获取当前用户可用积分
                
                $this->assign('integral_enabled',  $integral_enabled);
                $this->assign('integral_seller',  Conf::get('integral_seller'));#积分抵扣金额比例
            }
            $this->_config_seo('title', Lang::get('confirm_order') . ' - ' . Conf::get('site_title'));
            $this->_curlocal(
                    LANG::get('create_order')
            );
            /* 获取我的收货地址 */
            $user_id=$this->visitor->get('user_id');
            if(!$user_id){
                $this->show_warning('login_please');
                return;
            }
            $delivery_data['my_address'] = $address_model->find(array(
                'conditions' => 'user_id=' . $user_id,
                'order' => 'is_default desc'
                    )
            );
            $delivery_data['addresses'] = ecm_json_encode($delivery_data['my_address']);
            $regions = $model_region->get_list(0);
            if ($regions) {
                $tmp = array();
                foreach ($regions as $key2 => $value) {
                    $tmp[$key2] = $value['region_name'];
                }
                $regions = $tmp;
            }
            
            $delivery_data['regions'] = $regions;


            $this->assign('delivery_data', $delivery_data);
            $this->assign('goods_info_array', $goods_info_array);
            //获取所有地区
            $all_regions_=$model_region->find();
            foreach($all_regions_ as $val){
                $all_regions[$val['region_id']]= array_merge($this->get_parent($val['parent_id'],$all_regions_),array(0));
            }
            $this->assign('all_regions',ecm_json_encode($all_regions));
            $this->display('order.form.html');
        } else {
            $model_order = & m('order');
            $model_member = & m('member');
            import('mobile_msg.lib');
            $mobile_msg = new Mobile_msg();
            $coupon_mod = & m('couponsn');
            $goods_mod = & m('goods');
            $member_mod = & m('member');
            import('integral.lib');
            $integral = new Integral();
            $goods_type = & gt($goods_info['type']);
            $order_type = & ot($goods_info['otype']);
//            lichen 2019/4/24 start
            $goods_spec_mod = & m('goodsspec');
            $storestock_mod = & m('storestock');
            $tax_mod = & m('my_tax');
            $unit_mod = & m('unit');
            $order_goods_mod =  & m('ordergoods');
            $order_extm_mod = & m('orderextm');
            $country_mod = & m('country_info');
            $wrap_mod = & m('wrap');
//            lichen 2019/4/24 end
            $order_log =& m('orderlog');
            $model_goodsstatistics = & m('goodsstatistics');
            
            $member_info = $member_mod->get($this->visitor->get('user_id'));
//            lichen 2019/5/23 start
            if(!$member_info['user_no'] || !$member_info['real_name'] || !$member_info['phone_mob']){
                $this->show_warning('请先个人中心完善您的身份信息', 'go_back', 'index.php?app=member&amp;act=profile');
                return;
            }
//            lichen 2019/5/23 end

            $coupon_sn_array=$_POST['coupon_sn'];
            $use_integral_array=$_POST['use_integral'];
            $order_id_array='';
            
            /****change foreach开始****/
            foreach($goods_info_array as $key => $goods_info){
                $member_mod->db->query('start transaction');
            /* 在此获取生成订单的两个基本要素：用户提交的数据（POST），商品信息（包含商品列表，商品总价，商品总数量，类型），所属店铺 */
            if ($goods_info === false) {
                /* 购物车是空的 */
                $member_mod->db->query('rollback');
                $this->show_warning('goods_empty');

                return;
            }
            /* 优惠券数据处理 */
            if ($goods_info['allow_coupon'] && !empty($coupon_sn_array)) {

                if(!empty($coupon_sn_array[$key])){
                $coupon = $coupon_mod->get(array(
                    'fields' => 'coupon.*,couponsn.remain_times',
                    'conditions' => "coupon_sn.coupon_sn = '".$coupon_sn_array[$key]."' AND coupon.store_id = " . $goods_info['store_id'],
                    'join' => 'belongs_to_coupon'));
                if (empty($coupon)) {
                    $member_mod->db->query('rollback');
                    $this->show_warning('involid_couponsn');
                    exit;
                }
                if ($coupon['remain_times'] < 1) {
                    $member_mod->db->query('rollback');
                    $this->show_warning("times_full");
                    exit;
                }
                $time = gmtime();
                if ($coupon['start_time'] > $time) {
                    $member_mod->db->query('rollback');
                    $this->show_warning("coupon_time");
                    exit;
                }

                if ($coupon['end_time'] < $time) {
                    $member_mod->db->query('rollback');
                    $this->show_warning("coupon_expired");
                    exit;
                }
                if ($coupon['min_amount'] > $goods_info['amount']) {
                    $member_mod->db->query('rollback');
                    $this->show_warning("amount_short");
                    exit;
                }
                unset($time);
                $goods_info_array[$key]['discount'] = $coupon['coupon_value'];
            }
            }
            if (!empty($use_integral_array[$key]) && $integral_enabled && intval($use_integral_array[$key])) {
                //用户提交使用的积分额度
                $use_integral=intval($use_integral_array[$key]);
                $total_integral_max_exchange = 0; #共可使用多少积分进行抵扣
                foreach ($goods_info['items'] as $goods) {
                    // 因为一个订单可能包含多个商品,一个商品可能购买了M件，那么可使用的积分便是 N*M 之和
                    $goods_integral = $goods_mod->get($goods['goods_id']); #当前产品设置的积分抵扣额
                    $total_integral_max_exchange += $goods_integral['integral_max_exchange'] * $goods['quantity'];
                }
                $goods_info_array[$key]['total_integral_max_exchange']=$total_integral_max_exchange;
                if ($use_integral > $total_integral_max_exchange) {
                    $member_mod->db->query('rollback');
                    $this->show_warning('can_used_up ' . $total_integral_max_exchange . 'integral'.'。');
                    exit;
                }
                //获取当前用户可用积分

                if ($use_integral > $member_info['integral']) {
                    $member_mod->db->query('rollback');
                    $this->show_warning('you_donnot_enough_points' . $member_info['integral']);
                    exit;
                }
                //获取抵扣金额
                $goods_info_array[$key]['discount'] += $use_integral * Conf::get('integral_seller');
                //扣除积分记录,更新信息

                if(!$integral->change_integral_seller($this->visitor->get('user_id'), $use_integral)){
                    $member_mod->db->query('rollback');
                    $this->show_warning('you_donnot_enough_points');
                    exit;
                }
            }

            $_post_data=array();
            $_post_data['address_options']=$_POST['address_options'];
            $_post_data['consignee']=$_POST['consignee'];
            $_post_data['region_id']=$_POST['region_id'];
            $_post_data['region_name']=$_POST['region_name'];
//          lichen 2019/4/12 start
            $_post_data['user_no']=$_POST['user_no'];
//          lichgen 2019/4/12 end
            $_post_data['address']=$_POST['address'];
            $_post_data['zipcode']=$_POST['zipcode'];
            $_post_data['phone_mob']=$_POST['phone_mob'];
            $_post_data['shipping_id']=$_POST['shipping_id_'.$key];
            $_post_data['is_free_fee']=$_POST['is_free_fee_'.$key];
            $_post_data['postscript']=$_POST['postscript'][$key];
            $_post_data['use_integral']=$_POST['use_integral'][$key];
            $_post_data['coupon_sn']=$_POST['coupon_sn'][$key];
            $_post_data['pd_amount']=$_POST['pd_amount'];
            /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
            $order_id = $order_type->submit_order(array(
                'goods_info' => $goods_info_array[$key], //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
                'post' => $_post_data, //用户填写的订单信息
            ));

                if (!$order_id) {
                $member_mod->db->query('rollback');
                $this->show_warning($order_type->get_error());
                return;
            }

            /* 下单完成后清理商品，如清空购物车，或将团购拍卖的状态转为已下单之类的 */
            $this->_clear_goods($order_id,$_POST['coupon_sn'][$key]);



                /* 减去商品库存 */
            $model_order->change_stock('-', $order_id);
            $member_mod->db->query('commit');
            /* 获取订单信息 */
            $order_info = $model_order->get($order_id);
            /* 记录订单操作日志 */
            $order_log->add(array(
                'order_id'  => $order_id,
                'operator'  => addslashes($this->visitor->get('user_name')),
                'order_status' => '',
                'changed_status' => Lang::get('Place_Order'),
                'remark'    => Lang::get('buyer_place_order'),
                'log_time'  => gmtime(),
                'operator_type'=>'buyer'
            ));
            
            /* 发送事件 */
            $feed_images = array();
            foreach ($goods_info['items'] as $_gi) {
                $feed_images[] = array(
                    'url' => SITE_URL . '/' . $_gi['goods_image'],
                    'link' => SITE_URL . '/' . url('app=goods&id=' . $_gi['goods_id']),
                );
            }
            $this->send_feed('order_created', array(
                'user_id' => $this->visitor->get('user_id'),
                'user_name' => addslashes($this->visitor->get('user_name')),
//                lichen 2019/4/12 start
                'buyer_no' => addslashes($this->visitor->get('user_no')),
                'phone_mob' => addslashes($this->visitor->get('phone_mob')),
//                lichen 2019/4/12 end
                'seller_id' => $order_info['seller_id'],
                'seller_name' => $order_info['seller_name'],
                'store_url' => SITE_URL . '/' . url('app=store&id=' . $order_info['seller_id']),
                'images' => $feed_images,
            ));

            $buyer_address = $this->visitor->get('email');
            $seller_info = $model_member->get($goods_info['store_id']);
            $seller_address = $seller_info['email'];

            /* 发送给买家下单通知 */
            $buyer_mail = get_mail('tobuyer_new_order_notify', array('order' => $order_info));
            $this->_mailto($buyer_address, addslashes($buyer_mail['subject']), addslashes($buyer_mail['message']));

            /* 发送给卖家新订单通知 */
            $seller_mail = get_mail('toseller_new_order_notify', array('order' => $order_info));
            $this->_mailto($seller_address, addslashes($seller_mail['subject']), addslashes($seller_mail['message']));

            /* 更新下单次数 */
            $goods_ids = array();
            foreach ($goods_info['items'] as $goods) {
                $goods_ids[] = $goods['goods_id'];
            }
            $model_goodsstatistics->edit($goods_ids, 'orders=orders+1');
            
            /* 到收银台付款 */
            
            
            //买家下单发送短信给卖家

            $mobile_msg->send_msg_order($order_info,'buy');
                if($order_id_array==''){
                    $order_id_array.=$order_id;
                }else{
                    $order_id_array.=','.$order_id;
                }
                
            }
//            lichen 2019/4/24 start
            /* 获取订单明细信息 */
            $order_goods = $order_goods_mod->find(array(
                'conditions' => "order_id=" . $order_id,
            ));
            $order_extm = $order_extm_mod->get('order_id='.$order_id);
            $send_data = $order_info;
            $send_data['order_goods'] = $order_goods;
            $send_data['order_extm'] = $order_extm;
            /* 获取商品明细信息 */
//            $send_data['goods_spec'] = array();
//            $send_data['goods'] = array();
//
//
//            $send_data['goods'] = array();
//            $send_data['storestock'] = array();
//            $send_data['tax'] = array();
//            $send_data['unit'] = array();
            foreach ($send_data['order_goods'] as $k=>$v){
                $temp_goods_spec = $goods_spec_mod->get('spec_id='.$send_data['order_goods'][$k]['spec_id']);
                $temp_goods = $goods_mod->get('goods_id='.$send_data['order_goods'][$k]['goods_id']);
//                var_dump($temp_goods);exit;
                $temp_storestock = $storestock_mod->get('storestock_id='.$temp_goods_spec['spec_3value']);
                $temp_tax = $tax_mod->get('tax_id='.$temp_goods['tax_id']);
                $temp_unit = $unit_mod->get('id='.$temp_goods['unit_id']);
                $temp_country = $country_mod->get('id='.$temp_goods['country_id']);
                $temp_wrap= $wrap_mod->get('id='.$temp_goods['wrap_id']);
                $send_data['order_goods'][$k]['spec'] = $temp_goods_spec;
                $send_data['order_goods'][$k]['goods'] = $temp_goods;
                $send_data['order_goods'][$k]['storestock'] = $temp_storestock;
                $send_data['order_goods'][$k]['tax'] = $temp_tax;
                $send_data['order_goods'][$k]['unit'] = $temp_unit;
                $send_data['order_goods'][$k]['country'] = $temp_country;
                $send_data['order_goods'][$k]['wrap'] = $temp_wrap;
//                array_push($send_data['order_goods'],$temp_goods_spec);
//                array_push($send_data['goods'],$temp_goods);
//                array_push($send_data['storestock'],$temp_storestock);
//                array_push($send_data['tax'],$temp_tax);
//                array_push($send_data['unit'],$temp_unit);
            }

//            echo json_encode($send_data);exit;

//            $send_data = $this->_($order_good);

            $sen_data = $this->_get_oms_data($send_data);
//            lichen 2019/4/22 start
            $url = OMS_URL; #url 地址必须 http://xxxxx
            $port = OMS_PORT;
            $t=30;
            $this->_post_to_oms($url,$port,$t,'post',$sen_data);
//            lichen 2019/4/22 end
//            lichen 2019/4/24 end
            /****change foreach结束****/
            /*  检查是否添加收货人地址  */
            if (isset($_POST['save_address']) && (intval(trim($_POST['save_address'])) == 1)) {
                $data = array(
                    'user_id' => $this->visitor->get('user_id'),
//                  lichen 2019/4/11 start
                    'user_no' => $_POST['user_no'],
//					lichen 2019/4/11 end
                    'consignee' => trim($_POST['consignee']),
                    'region_id' => $_POST['region_id'],
                    'region_name' => $_POST['region_name'],
                    'address' => trim($_POST['address']),
                    'zipcode' => trim($_POST['zipcode']),
                    'phone_mob' => trim($_POST['phone_mob']),
                );
                $model_address = & m('address');
                $model_address->add($data);
            }
            /* 到收银台付款 */
            //change 使用order_id_array
            if($_GET['goods']=='single' || !strpos($order_id_array,','))
            {
                header('Location:index.php?app=cashier&order_id=' . $order_id_array); 
                exit;
            }else{
                header('Location:index.php?app=cashier&order_id_array=' . $order_id_array); 
                exit;
            }
        }
    }
    function get_parent($parent_id,$all_regions_){
        $all_regions=array();
        if($parent_id){
                $all_regions=array_merge($all_regions,$this->get_parent($all_regions_[$parent_id]['parent_id'],$all_regions_));
                $all_regions[]=$parent_id;
        }
        return $all_regions;
    }
    /**
     *    获取外部传递过来的商品
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function _get_goods_info() {
        $return = array(
        );
        switch ($_GET['goods']) {
            case 'groupbuy':
                /* 团购的商品 */
                $group_id = isset($_GET['group_id']) ? intval($_GET['group_id']) : 0;
                $user_id = $this->visitor->get('user_id');
                if (!$group_id || !$user_id) {
                    return false;
                }
                /* 获取团购记录详细信息 */
                $model_groupbuy = & m('groupbuy');
                $groupbuy_info = $model_groupbuy->get(array(
                    'join' => 'be_join, belong_store, belong_goods',
                    'conditions' => $model_groupbuy->getRealFields("groupbuy_log.user_id={$user_id} AND groupbuy_log.group_id={$group_id} AND groupbuy_log.order_id=0 AND this.state=" . GROUP_FINISHED),
                    'fields' => 'store.store_id, store.store_name, goods.goods_id, goods.goods_name, goods.default_image, groupbuy_log.quantity, groupbuy_log.spec_quantity, this.spec_price',
                ));

                if (empty($groupbuy_info)) {
                    return false;
                }

                /* 库存信息 */
                $model_goodsspec = &m('goodsspec');
                $goodsspec = $model_goodsspec->find('goods_id=' . $groupbuy_info['goods_id']);

                /* 获取商品信息 */
                $spec_quantity = unserialize($groupbuy_info['spec_quantity']);
                $spec_price = unserialize($groupbuy_info['spec_price']);
                $amount = 0;
                $groupbuy_items = array();
                $goods_image = empty($groupbuy_info['default_image']) ? Conf::get('default_goods_image') : $groupbuy_info['default_image'];
                foreach ($spec_quantity as $spec_id => $spec_info) {
                    $the_price = $spec_price[$spec_id]['price'];
                    $subtotal = $spec_info['qty'] * $the_price;
                    $groupbuy_items[] = array(
                        'goods_id' => $groupbuy_info['goods_id'],
                        'goods_name' => $groupbuy_info['goods_name'],
                        'spec_id' => $spec_id,
                        'specification' => $spec_info['spec'],
                        'price' => $the_price,
                        'quantity' => $spec_info['qty'],
                        'goods_image' => $goods_image,
                        'subtotal' => $subtotal,
                        'stock' => $goodsspec[$spec_id]['stock'],
                    );
                    $amount += $subtotal;
                }

                $return[$groupbuy_info['store_id']]['items'] = $groupbuy_items;
                $return[$groupbuy_info['store_id']]['quantity'] = $groupbuy_info['quantity'];
                $return[$groupbuy_info['store_id']]['amount'] = $amount;
                $return[$groupbuy_info['store_id']]['store_id'] = $groupbuy_info['store_id'];
                $return[$groupbuy_info['store_id']]['store_name'] = $groupbuy_info['store_name'];

                $return[$groupbuy_info['store_id']]['allow_coupon'] = false;
                $return[$groupbuy_info['store_id']]['free_shipping'] = ecm_json_encode($free_shipping);
                
                $return[$groupbuy_info['store_id']]['type'] = 'material';
                $return[$groupbuy_info['store_id']]['otype'] = 'groupbuy';
                break;
            default:
                /* 从购物车中取商品 */
                if($_GET['goods']=='single'){
                    require(ROOT_PATH . '/app' . "/cart.app.php");
                    $app = new CartApp();
					Lang::load(lang_file('cart'));
                    $cart_items=$app->add();
                    if(!is_array($cart_items)){
                        $cart_items=array();
                    }else{
						$cart_items[0]['specification']=stripslashes($cart_items[0]['specification']);
					}
                }else{
                $cart_model = & m('cart');

                /*
                $cart_items = $cart_model->find(array(
                    'conditions' => "user_id = " . $this->visitor->get('user_id') . " AND store_id = {$store_id} AND session_id='" . SESS_ID . "'",
                    'join' => 'belongs_to_goodsspec',
                ));
                 */
                    if($_GET['batch']){
                        if($_GET['rec_ids']){
                            $conditions=' AND rec_id IN ('.$_GET['rec_ids'].')';
                        }else{
                            $conditions=' AND 1=2';
                        }
                    }
                $cart_items = $cart_model->find(array(
                    'conditions' => "user_id = " . $this->visitor->get('user_id') . " AND session_id='" . SESS_ID . "'".$conditions,
                    'join' => 'belongs_to_goodsspec',
                    'fields' => 'gs.spec_id,gs.spec_1,gs.spec_1value,gs.spec_2,gs.color_rgb,gs.stock,gs.sku,cart.*' // 不能有 gs.price， 要不读取的不是促销价格，购物车里面才是促销价格
                ));
                }
                if (empty($cart_items)) {
                    return false;
                }


                $store_model = & m('store');
                foreach ($cart_items as $rec_id => $goods) {
                    if(empty($return[$goods['store_id']])){
                        $store_info = $store_model->get($goods['store_id']);
                        $return[$goods['store_id']]=array();
                        $return[$goods['store_id']]['allow_coupon'] = true;
                        $return[$goods['store_id']]['store_id'] = $goods['store_id'];
                        $return[$goods['store_id']]['store_name'] = $store_info['store_name'];
                        $return[$goods['store_id']]['store_im_qq'] = $store_info['im_qq']; //  
                        $return[$goods['store_id']]['type'] = 'material';
                        $return[$goods['store_id']]['enable_free_fee'] = $store_info['enable_free_fee'];
                        $return[$goods['store_id']]['amount_for_free_fee'] = $store_info['amount_for_free_fee'];
                        $return[$goods['store_id']]['acount_for_free_fee'] = $store_info['acount_for_free_fee'];
                        $return[$goods['store_id']]['otype'] = 'normal';
                        $return[$goods['store_id']]['free_shipping']=ecm_json_encode($free_shipping);
                        
                    }
                    //判断购物车的价格是否有效待完善
                    $return[$goods['store_id']]['quantity'] += $goods['quantity'];                      //商品总量
//                    lichen 2019/4/18 start
//                    $return[$goods['store_id']]['amount'] += $goods['quantity'] * $goods['price'];    //商品总价
                    $return[$goods['store_id']]['amount'] += $goods['quantity'] * $goods['price'] + $goods['quantity'] * $goods['tax_price'];    //商品总价
//                    lichen 2019/4/18 end
//                    lichen 2019/4/18 start
                    $cart_items[$rec_id]['subtotal'] = $goods['quantity'] * $goods['price'] + $goods['quantity'] * $goods['tax_price'];   //小计
//                    $cart_items[$rec_id]['subtotal'] = $goods['quantity'] * $goods['price'];   //小计
//                    lichen 2019/4/8 end
                    empty($goods['goods_image']) && $cart_items[$rec_id]['goods_image'] = Conf::get('default_goods_image');
                    $return[$goods['store_id']]['items'][$rec_id] = $cart_items[$rec_id];
                }

                break;
        }

        return $return;
    }

    /**
     *    下单完成后清理商品
     *
     *    @author    Garbin
     *    @return    void
     */
    function _clear_goods($order_id,$coupon_sn) {
        switch ($_GET['goods']) {
            case 'single':
                break;
            case 'groupbuy':
                /* 团购的商品 */
                $model_groupbuy = & m('groupbuy');
                $model_groupbuy->updateRelation('be_join', intval($_GET['group_id']), $this->visitor->get('user_id'), array(
                    'order_id' => $order_id,
                ));
                break;
            default://购物车中的商品
                /* 订单下完后清空指定购物车 */
                    if($_GET['batch']){
                        if($_GET['rec_ids']){
                            $conditions=' AND rec_id IN ('.$_GET['rec_ids'].')';
                        }else{
                            $conditions=' AND 1=2';
                        }
                    }
                $model_cart = & m('cart');
                $model_cart->drop("session_id='" . SESS_ID . "'".$conditions);

                break;
        }
                //优惠券信息处理
                if (!empty($coupon_sn)) {
                    $sn = trim($coupon_sn);
                    $couponsn_mod = & m('couponsn');
                    $couponsn = $couponsn_mod->get("coupon_sn = '{$sn}'");
                    if ($couponsn['remain_times'] > 0) {
                        $couponsn_mod->edit("coupon_sn = '{$sn}'", "remain_times= remain_times - 1");
                    }
                }
    }

    /**
     * 检查优惠券有效性
     */
    function check_coupon() {
        $coupon_sn = $_GET['coupon_sn'];
        $store_id = is_numeric($_GET['store_id']) ? $_GET['store_id'] : 0;
        if (empty($coupon_sn)) {
            $this->js_result(false);
        }
        $coupon_mod = & m('couponsn');
        $coupon = $coupon_mod->get(array(
            'fields' => 'coupon.*,couponsn.remain_times',
            'conditions' => "coupon_sn.coupon_sn = '{$coupon_sn}' AND coupon.store_id = " . $store_id,
            'join' => 'belongs_to_coupon'));
        if (empty($coupon)) {
            $this->json_result(false);
            exit;
        }
        if ($coupon['remain_times'] < 1) {
            $this->json_result(false);
            exit;
        }
        $time = gmtime();
        if ($coupon['start_time'] > $time) {
            $this->json_result(false);
            exit;
        }


        if ($coupon['end_time'] < $time) {
            $this->json_result(false);
            exit;
        }

        // 检查商品价格与优惠券要求的价格

        $model_cart = & m('cart');
        $item_info = $model_cart->find("store_id={$store_id} AND session_id='" . SESS_ID . "'");
        $price = 0;
        foreach ($item_info as $val) {
            $price = $price + $val['price'] * $val['quantity'];
        }
        if ($price < $coupon['min_amount']) {
            $this->json_result(false);
            exit;
        }
        $this->json_result(array('res' => true, 'price' => $coupon['coupon_value']));
        exit;
    }

    function _check_beyond_stock($goods_items) {
        $goods_beyond_stock = array();
        foreach ($goods_items as $rec_id => $goods) {
            if ($goods['quantity'] > $goods['stock']) {
                $goods_beyond_stock[$goods['spec_id']] = $goods;
            }
        }
        return $goods_beyond_stock;
    }

//    lichen 2019/4/24 start

    function _get_oms_data($data = array()){
        $return_array['OrderItets'] = array();
        foreach ($data['order_goods'] as $k => $v) {
            if(!array_key_exists($data['order_goods'][$k]['goods']['goods_id'],$return_array['OrderItets'])){
//                if(!array_search($data[$k]['spec'],$return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'],true)){
//                    if(!isset($return_array[$v['goods_id']]['OrderItemDetails'])){
//                        $return_array[$v['goods_id']]['OrderItemDetails'] = array();
//                    }
//                $return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'] = array();
                $return_array['OrderItets'][$v['goods_id']]['ProductId'] = $data['order_goods'][$k]['goods']['goods_id'];
                $return_array['OrderItets'][$v['goods_id']]['ItemName'] = '爱莎';
                $return_array['OrderItets'][$v['goods_id']]['Unit'] = $data['order_goods'][$k]['unit']['unit_code'];
                $return_array['OrderItets'][$v['goods_id']]['Currency'] = '142';
                $return_array['OrderItets'][$v['goods_id']]['CiqCurrency'] = '156';
                $return_array['OrderItets'][$v['goods_id']]['Country'] = $data['order_goods'][$k]['country']['country_code'];
                $return_array['OrderItets'][$v['goods_id']]['CiqCountry'] = $data['order_goods'][$k]['country']['ciq_code'];
                $return_array['OrderItets'][$v['goods_id']]['WrapTypeCode'] = $data['order_goods'][$k]['wrap']['wrap_code'];
                //                test
                $return_array['OrderItets'][$v['goods_id']]['PurposeCode'] = '9';
                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = $data['seller_id'];
                $return_array['OrderItets'][$v['goods_id']]['StoreId'] = $data['seller_id'];
//                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = 16;

                $return_array['OrderItets'][$v['goods_id']]['ShelfGoodsName'] = $data['brand'];

                $return_array['OrderItets'][$v['goods_id']]['ProductSku'] = 'none';
                $return_array['OrderItets'][$v['goods_id']]['BarCode'] = 'none';


                }
            $return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'][] = array(
                'AttributeSku' => $data['order_goods'][$k]['spec']['sku'],
                'Quantity' => $data['order_goods'][$k]['quantity'],
                'Price' => $data['order_goods'][$k]['spec']['price'],
                'TaxRates' => $data['order_goods'][$k]['tax']['consolidated_tax'],
                'OrderTax' => $data['order_goods'][$k]['tax_price'],
                'OrderDiscount' => 0,
                'BarCode' => $data['order_goods'][$k]['spec']['barcode'],
                'TradeType' => $data['order_goods'][$k]['storestock']['stock_style'],
            'PriceInclTax' => $data['order_goods'][$k]['goods']['price'],
                'TotalPrice' => $data['order_goods'][$k]['price_total'],
//                test
                'CustomsChannelId' =>  $data['order_goods'][$k]['storestock']['stock_id'],
//                'CustomsChannelId' =>  12,
            );
//                    $return_array[$v['goods_id']][''] = array()
//                array_push($return_array[$v['']]['OrderItemDetails'][''],);
//            }else{
//                $return_array['OrderItets'][$v['goods_id']] = array();

//            }
        }
        $address_str = $this->emptyreplace($data['order_extm']['region_name']);
        $address_str = $address_str . $data['order_extm']['address'];
        $return_array['OrderStatusId'] = 10;
        $return_array['ShippingStatusId'] = 20;
        $return_array['PaymentStatusId'] = 10;
        $return_array['PaymentMethodSystemName'] = 'none';
        $return_array['ShippingMethod'] = 'ground';
        $return_array['CustomerCurrencyCode'] = '142';
        $return_array['AuthorizationTransactionResult'] = 'none';
        $return_array['OrderTotal'] = $data['goods_amount'];
        $return_array['AffiliateId'] = 0;
        $return_array['RefundedAmount'] = 0;
        $return_array['CreatedOnUtc'] = date("Y-m-d H:i:s");
        $return_array['OrderNo'] = $data['order_sn'];
        $return_array['BuyerName'] = $this->visitor->get('real_name');
        $return_array['BuyerTelephone'] = $data['phone_mob'];
        $return_array['BuyerRegNo'] = $data['phone_mob'];
        $return_array['BuyerIdType'] = 1;
        $return_array['BuyerIdNumber'] = $this->visitor->get('user_no');
        $return_array['PayCode'] = 'none';
        $return_array['PayName'] = 'none';
        $return_array['PayTransactionId'] = 'none';
        $return_array['Consignee'] = $data['order_extm']['consignee'];
        $return_array['ConsigneeTelephone'] = $data['order_extm']['phone_mob'];
        $return_array['ConsigneeAddress'] = $address_str;
        $return_array['IdCard'] = $data['order_extm']['user_no'];
        $return_array['IdType'] = 1;
        $return_array['EtradeCountryCode'] = '156';
        $return_array['OrderItems'] = array();
        $return_array['OrderItems'] = array_values($return_array['OrderItets']);
        return $return_array;

    }
    function _post_to_oms($url,$port=80,$t=30,$method='get',$data=null)
    {
        $info=parse_url($url);
        $fp = fsockopen('ssl://'.$info['host'],$port,$errno,$errstr,$t);
        // 判断是否有数据
        if(isset($data) && !empty($data))
        {
            $query = http_build_query($data); // 数组转url 字符串形式
        }else
        {
            $query=null;
        }
        // 如果用户的$url "http://www.manongjc.com/";  缺少 最后的反斜杠
        if(!isset($info['path']) || empty($info['path']))
        {
            $info['path']="/index.html";
        }
        // 判断 请求方式
        if($method=='post')
        {
            $head = "POST ".$info['path']." HTTP/1.0".PHP_EOL;
        }else
        {
            $head = "GET ".$info['path']."?".$query." HTTP/1.0".PHP_EOL;
        }

        $head .= "Host: ".$info['host'].PHP_EOL; // 请求主机地址
        $head .= "Referer: https://".$info['host'].':'.$port.$info['path'].PHP_EOL;
        if(isset($data) && !empty($data) && ($method=='post'))
        {
            $head .= "Content-type: application/x-www-form-urlencoded".PHP_EOL;
            $head .= "Content-Length: ".strlen(trim($query)).PHP_EOL;
            $head .= PHP_EOL;
            $head .= trim($query);
        }else
        {
            $head .= PHP_EOL;
        }
//        var_dump($head);exit;
        $write = fputs($fp, $head); //写入文件(可安全用于二进制文件)。 fputs() 函数是 fwrite() 函数的别名
        while (!feof($fp))
        {
            $line = fread($fp,4096);
            echo $line;
        }
    }
//    lichen 2019/4/24 end
    function emptyreplace($str)
    {
        $str = preg_replace('/\s+/',',',$str);
        return $str;
    }
}

?>
